import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import '../../public/repeat_fun.dart';
import 'package:provider/provider.dart';
import '../../http/index.dart';
import '../../provider/vipPayment.dart';

class PaymentVip extends StatefulWidget {
  PaymentVip({Key key}) : super(key: key);

  @override
  _PaymentVipState createState() => _PaymentVipState();
}

class _PaymentVipState extends State<PaymentVip> {
  @override
  void initState() {
    super.initState();
    _initFluwx();
  }

  _initFluwx() async {
    await fluwx.registerWxApi(
        appId: "wx3b404fa81f1e2843",
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "https://your.univerallink.com/link/");
    var result = await fluwx.isWeChatInstalled;
    print("is installed $result");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          height: double.infinity,
          width: double.infinity,
          color: Color(0xff262434),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(25.w, 0, 25.w, 0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    UserInfo(),
                    OptionVip(),
                    PaymentOption(),
                  ],
                ),
              ),
              ConfirmPayment(),
            ],
          )),
    );
  }
}

class UserInfo extends StatefulWidget {
  UserInfo({Key key}) : super(key: key);

  @override
  _UserInfoState createState() => _UserInfoState();
}

class _UserInfoState extends State<UserInfo> {
  userInfo(data) {
    var infoData = data;
    return Container(
      padding: EdgeInsets.fromLTRB(0, 25.h, 0, 0),
      child: Column(
        children: [
          ClipOval(
            child: Image.network(
              infoData['data']['head_img'] == ''
                  ? 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3363295869,2467511306&fm=26&gp=0.jpg'
                  : infoData['data']['head_img'],
              fit: BoxFit.fill,
              width: 125.w,
              height: 125.w,
            ),
          ),
          SizedBox(height: 20.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                infoData['data']['name'],
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 35.sp,
                ),
              ),
              Text(
                (' (${infoData['data']['school']['name']})'),
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 35.sp,
                ),
              ),
            ],
          ),
          Text(
            infoData['data']['is_vip'] != 0
                ? "有效期: ${infoData['data']['is_vip']}"
                : '未开通',
            style: TextStyle(color: Colors.white60),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.fromLTRB(0, 55.h, 0, 0),
        height: 300.h,
        width: double.infinity,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
              left: 0,
              top: 25.h,
              child: IconButton(
                icon: Icon(
                  Icons.keyboard_arrow_left,
                  color: Colors.white,
                ),
                alignment: Alignment.center,
                onPressed: () {
                  Navigator.of(context).pop();
                },
                iconSize: 60.sp,
              ),
            ),
            RequertLoad(
                context, Http(context).postHttp('/auth/info', ''), userInfo),
          ],
        ));
  }
}

class OptionVip extends StatefulWidget {
  OptionVip({Key key}) : super(key: key);

  @override
  _OptionVipState createState() => _OptionVipState();
}

class _OptionVipState extends State<OptionVip> with TickerProviderStateMixin {
  TabController _tabController;
  option(data) {
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      Provider.of<VipPayment>(context, listen: false)
          .currenOptions(data['data'][0]['children'][0]);
    });
    List tabs = new List();
    List<Widget> itemCardList = new List();
    for (var i = 0; i <= data['data'].length - 1; i++) {
      tabs.add(data['data'][i]['name']);
      itemCardList.add(OptionItem(data['data'][i]['children']));
    }
    _tabController = TabController(length: tabs.length, vsync: this);
    return Scaffold(
      backgroundColor: Color(0xff262434),
      appBar: PreferredSize(
        child: AppBar(
          backgroundColor: Color(0xff262434),
          elevation: 0,
          leading: Text(''),
          bottom: TabBar(
            indicatorWeight: 1.0,
            indicatorSize: TabBarIndicatorSize.label,
            indicatorColor: Colors.yellow,
            labelColor: Colors.yellow,
            labelStyle: TextStyle(color: Colors.yellow, fontSize: 45.sp),
            controller: _tabController,
            tabs: tabs.map((e) => Tab(text: e)).toList(),
            onTap: (value) => {
              Provider.of<VipPayment>(context, listen: false)
                  .currenOptions(data['data'][value]['children'][0]),
            },
          ),
        ),
        preferredSize: Size.fromHeight(150.h),
      ),
      body: TabBarView(
        physics: NeverScrollableScrollPhysics(),
        controller: _tabController,
        children: itemCardList,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 500.h,
      width: double.infinity,
      child: RequertLoad(
          context, Http(context).postHttp('/gankao/vip', ''), option),
    );
  }
}

// 循环出每一个子项里面所有的卡片选项
class OptionItem extends StatefulWidget {
  var items;
  OptionItem(this.items);

  @override
  _OptionItemState createState() => _OptionItemState(items);
}

class _OptionItemState extends State<OptionItem> {
  var items;
  var index = 0;
  _OptionItemState(this.items);
  optionItem(items) {
    List<Widget> cardList = List();
    for (var i = 0; i < items.length; i++) {
      cardList.add(
        InkWell(
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 25.h, 0, 25.h),
            margin: EdgeInsets.fromLTRB(10.w, 0, 15.w, 0),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    i == index ? Color(0xfffad8a3) : Color(0xff41475c),
                    i == index ? Color(0xfffee6c3) : Color(0xff31324a),
                  ]),
              borderRadius: BorderRadius.all(
                Radius.circular(10.0),
              ),
            ),
            width: 210.w,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Text(
                  "${items[i]['name']}",
                  style: TextStyle(
                    color: i == index ? Color(0xff71562f) : Color(0xfff5dc9a),
                    fontSize: 40.sp,
                  ),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "￥",
                      style: TextStyle(
                        color:
                            i == index ? Color(0xff71562f) : Color(0xfff5dc9a),
                        fontSize: 35.sp,
                      ),
                    ),
                    Text(
                      "${items[i]['discount_price']}",
                      style: TextStyle(
                        color:
                            i == index ? Color(0xff71562f) : Color(0xfff5dc9a),
                        fontSize: 60.sp,
                      ),
                    ),
                  ],
                ),
                Text(
                  "￥${items[i]['original_price']}",
                  style: TextStyle(
                    color: i == index ? Color(0xffb29873) : Color(0xff968971),
                    fontSize: 30.sp,
                    decoration: TextDecoration.lineThrough,
                  ),
                ),
              ],
            ),
          ),
          onTap: () {
            setState(() {
              index = i;
            });
            Provider.of<VipPayment>(context, listen: false)
                .currenOptions(items[index]);
          },
        ),
      );
    }
    return Container(
      margin: EdgeInsets.fromLTRB(0, 35.h, 0, 0),
      color: Color(0xff262434),
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: cardList,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: optionItem(items),
    );
  }
}

class PaymentOption extends StatefulWidget {
  PaymentOption({Key key}) : super(key: key);

  @override
  _PaymentOptionState createState() => _PaymentOptionState();
}

class _PaymentOptionState extends State<PaymentOption> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 300.h,
      child: ListView(
        children: [
          ListTile(
            contentPadding: EdgeInsets.all(0),
            leading: Icon(Icons.ac_unit),
            title: Text('支付宝支付',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 35.sp,
                )),
            trailing: Container(
              margin: EdgeInsets.fromLTRB(0, 30.h, 10, 0),
              width: 35.w,
              height: 35.w,
              decoration: BoxDecoration(
                color: Provider.of<VipPayment>(context, listen: true)
                            .paymentType ==
                        1
                    ? Color(0xfff5dc9a)
                    : Color(0xff262434),
                border: Border.all(
                  color: Provider.of<VipPayment>(context, listen: true)
                              .paymentType ==
                          1
                      ? Color(0xfff5dc9a)
                      : Colors.white,
                ),
                borderRadius: BorderRadius.all(
                  Radius.circular(30.0),
                ),
              ),
              child: Text(""),
            ),
            onTap: () {
              Provider.of<VipPayment>(context, listen: false).setpayment(1);
            },
          ),
          ListTile(
            contentPadding: EdgeInsets.all(0),
            leading: Icon(Icons.ac_unit),
            title: Text('微信支付',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 35.sp,
                )),
            trailing: Container(
              margin: EdgeInsets.fromLTRB(0, 30.h, 10, 0),
              width: 35.w,
              height: 35.w,
              decoration: BoxDecoration(
                color: Provider.of<VipPayment>(context, listen: true)
                            .paymentType ==
                        2
                    ? Color(0xfff5dc9a)
                    : Color(0xff262434),
                border: Border.all(
                  color: Provider.of<VipPayment>(context, listen: true)
                              .paymentType ==
                          2
                      ? Color(0xfff5dc9a)
                      : Colors.white,
                ),
                borderRadius: BorderRadius.all(
                  Radius.circular(30.0),
                ),
              ),
              child: Text(""),
            ),
            onTap: () {
              Provider.of<VipPayment>(context, listen: false).setpayment(2);
            },
          ),
        ],
      ),
    );
  }
}

//底部的确认支付
class ConfirmPayment extends StatefulWidget {
  ConfirmPayment({Key key}) : super(key: key);

  @override
  _ConfirmPaymentState createState() => _ConfirmPaymentState();
}

class _ConfirmPaymentState extends State<ConfirmPayment> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(25.w, 0, 25.w, 0),
      height: 170.h,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xff414256),
            Color(0xff262434),
          ],
          stops: [0.1, 0.9],
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                "￥${Provider.of<VipPayment>(context, listen: true).discount_price}",
                style: TextStyle(
                  color: Color(0xfff5dc9a),
                  fontSize: 60.sp,
                ),
              ),
              SizedBox(width: 25.w),
              Text(
                "￥${Provider.of<VipPayment>(context, listen: true).original_price}",
                style: TextStyle(
                  color: Color(0xff968971),
                  fontSize: 30.sp,
                  decoration: TextDecoration.lineThrough,
                ),
              ),
            ],
          ),
          InkWell(
            child: Container(
              alignment: Alignment.center,
              width: 300.w,
              height: 100.h,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.bottomLeft,
                  end: Alignment.topRight,
                  colors: [
                    Color(0xfffee6c3),
                    Color(0xfffad8a3),
                  ],
                ),
                borderRadius: BorderRadius.all(
                  Radius.circular(30.0),
                ),
              ),
              child: Text(
                "立即开通",
                style: TextStyle(
                  color: Color(0xff71562f),
                  fontSize: 35.sp,
                ),
              ),
            ),
            onTap: () async {
              // var order = await Http(context).postHttp(
              //     '/gankao/vip/wechat?payment_client_type=app', {
              //   'vip_id': Provider.of<VipPayment>(context, listen: false).vipId,
              //   'code': ''
              // });
              // print("order${order}");
              // var pay = await Http(context).postHttp('/pay/wechat', {
              //   'id': Provider.of<VipPayment>(context, listen: false).vipId
              // });

              // fluwx.payWithWeChat(
              //   appId: null,
              //   partnerId: null,
              //   prepayId: null,
              //   packageValue: null,
              //   nonceStr: null,
              //   timeStamp: null,
              //   sign: null,
              // );
            },
          )
        ],
      ),
    );
  }
}
